//
        //  XCHomeTableViewController.swift
//  小陈微博Swift用纯代码创建
//
//  Created by 小陈 on 16/2/26.
//  Copyright © 2016年 小陈. All rights reserved.
//

import UIKit
private let ReusaId = "cellId"
class XCHomeTableViewController: XCBaseTableViewController {
/// 创建 空的 XCStatus 数组
    var statusArray: [XCStatus]? {
        didSet{
            tableView.reloadData()
        }
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        // 判断用户是否登录
        if !XCUSerAccountViewModel.sharedInstance.isUserLogin{
            return
        }
        
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
// 设置导航条上的控件
     setUpNavigationBar()
  // 注册cell
        
        tableView.registerClass(XCStatusCell.self, forCellReuseIdentifier: ReusaId)


        // 加载用户数据
//        loadNewStatus()
        
        // 预估值
        tableView.estimatedRowHeight = 150
        // 自适应高度
        tableView.rowHeight = UITableViewAutomaticDimension
        
       /*=====================刷新控件==============================*/
        /// 设置刷新控件
        refreshControl = XCRefreshControl()
        refreshControl?.addTarget(self, action: "loadNewStatus", forControlEvents: UIControlEvents.ValueChanged)
        refreshControl?.beginRefreshing()
        refreshControl?.sendActionsForControlEvents(UIControlEvents.ValueChanged)
    }
    
    
    // 加载最新的 微博数据的时候传递 since_id 和 max_id  给服务器
    func loadNewStatus(){
        
        let since_id = statusArray?.first?.id ?? 0
  
     statusVM.loadUserStatus(since_id, max_id: 0){ (statusResult, error) -> () in
        /*=====================刷新控件==============================*/
        ///  让刷新控件回到没有加载的状态
        self.refreshControl?.endRefreshing()
         /*=====================刷新控件==============================*/
        if error != nil{
            print(" 获取用户数据失败 error :\(error)")
            return
        }
        
        let count = statusResult!.count ?? 0
        print("加载count \(count)条微博数据")
        
        if count == 0{
            print("上拉刷新没有新的微博数据")
            
            return
        }
        
        if since_id == 0{
            self.statusArray = statusResult
        }else{
        
            self.statusArray = statusResult! + self.statusArray!
        }
//          print("\n\n\nself.statusArray--------------------: \(self.statusArray)")
        }
        

        
    }
    
    /// 加载更多的微博数据
    func loadMoreStatus(){
        let max_id = statusArray?.last?.id ?? 0
        
        statusVM.loadUserStatus(0, max_id: max_id) { (statusResult, error) -> () in
            let count = statusResult?.count
            
            if count == nil{
                print("没有更多的微博数据")
                return
            }

        }
    }
    
    
 //   MARK: - 设置导航条上的控件
    func setUpNavigationBar(){
        setNavigationBarItem()
        setUpNavigationBarTitle()
    }
    
    /**
    设置导航条上的按钮
    */
    func setNavigationBarItem(){
    navigationItem.leftBarButtonItem = UIBarButtonItem(ImageName: "navigationbar_friendsearch")
        

        navigationItem.rightBarButtonItem = UIBarButtonItem(ImageName: "navigationbar_pop")
        
        
        let button =  navigationItem.rightBarButtonItem?.customView as! UIButton
//        
//        button.addObserver(self, forKeyPath: "QRCodeBtn", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        
      button.addTarget(self, action: "QRCodeBtn", forControlEvents: UIControlEvents.TouchUpInside)

    }
    
    func QRCodeBtn(){
        print("我点击了二维码按钮")
        let sb = UIStoryboard(name: "QRCode", bundle: nil)
        
        presentViewController(sb.instantiateInitialViewController()!, animated: true, completion: nil)

    }
    
    
    
    // 设置title
    func setUpNavigationBarTitle(){
        let title = XCUSerAccountViewModel.sharedInstance.userAccount!.screen_name
        let button = XCTitleButton(title: title!)
        
        button.addTarget(self, action: "ClickTitleButton:", forControlEvents: UIControlEvents.TouchUpInside)
        
        navigationItem.titleView = button

    }
    
    
    //MARK: - 标题按钮的点击事件
    func ClickTitleButton(button: UIButton){
        button.selected = !button.selected
        print("你点击了标题按钮")
        
UIView.animateWithDuration(0.25, animations: { () -> Void in

    button.imageView?.transform = button.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.01)) :CGAffineTransformIdentity
    
       })
        if button.selected {
            
            // 当按钮选中的时候弹出Pop 菜单
            let PopMuneVC = XCPopverController()
            // 在Iphon 上面设置PopVerVC 默认弹出的样式是modal
            PopMuneVC.modalPresentationStyle = UIModalPresentationStyle.Popover
            PopMuneVC.popoverPresentationController?.delegate = self
            PopMuneVC.popoverPresentationController?.sourceView = navigationItem.titleView
            PopMuneVC.popoverPresentationController?.sourceRect = (navigationItem.titleView?.bounds)!
            PopMuneVC.preferredContentSize = CGSizeMake(200, 5 * 44)
            presentViewController(PopMuneVC, animated: true, completion: nil)
        }
    }
    // MARK: - 懒加载 创建 XCStatusViewModel 对象
    private lazy var statusVM: XCStatusViewModel = XCStatusViewModel()
    
}
    //MARK: - 实现 Poper 的数据源
extension XCHomeTableViewController : UIPopoverPresentationControllerDelegate {
    // 让iPhone上面可以显示popover效果
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
        return UIModalPresentationStyle.None
    }
    
    func popoverPresentationControllerDidDismissPopover(popoverPresentationController: UIPopoverPresentationController) {
        let ClickButton = navigationItem.titleView as! XCTitleButton
        ClickTitleButton(ClickButton)
    }
}


 // MARK: - Table view data source
extension XCHomeTableViewController {
   
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        
        return 1
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // ?? 表示前面可选有值就拆包 没值使用 ?? 后面的值
        
        return self.statusArray?.count ?? 0
       
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
      let cell =  tableView.dequeueReusableCellWithIdentifier(ReusaId, forIndexPath: indexPath) as! XCStatusCell

        cell.status = statusArray?[indexPath.row]
        return cell
    }
    
    override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return false
    }
    
//    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//    {
//    return [tableView fd_heightForCellWithIdentifier:@"identifer" cacheByIndexPath:indexPath configuration:^(id cell) {
//    // configurations
//    }];
//    }
    
//    func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
//        
//    }
    
}



